<script setup>
import {ref} from "vue";
import { useRouter, useRoute } from "vue-router";
import {ElLoading, ElMessage} from "element-plus";
import {http} from "@/api";
import { defaultMockMenu } from "@/utils/common";

const apiKey = 'role'
const router = useRouter()
const route = useRoute()
const id = route.params.id
const menuList = ref(defaultMockMenu.map(el => {
  return {
    ...el,
    checked: !id,
    children: el.children ? (el.children || []).map(sub => {
      return {
        ...sub,
        checked: false
      }
    }): [
      {
        ...el,
        checked: false
      }
    ]
  }
}))

const formData = ref({
  "menu": [],
  "name": ""
})

const rules = ref({
  name: [
    { required: true, message: '请输入', trigger: 'blur' },
  ],
})

const formRef =  ref(null)
if (id) {
  // 获取详情
  http[apiKey].read({
    id
  }).then(res => {
    res.data.menu = res.data.menu.split(',')
    for (const valueKey in formData.value) {
      formData.value[valueKey] = res.data[valueKey]
    }
    formData.value.id = id
    menuList.value.forEach(el => {
      if (el.children) {
        el.children.forEach(el2 => {
          if (res.data.menu.includes(el2.code)) {
            el2.checked = true
          }
        })
      }
    })
  })
}
const cancel = () => {
  router.back()
}
const confirm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      let checkedMenu = []
      menuList.value.forEach(el => {
        el.children.forEach(el2 => {
          if (el2.checked) {
            checkedMenu.push(el2.code)
          }
        })
      })
      const loadingInstance = ElLoading.service()
      if (id) {
        // 编辑
        http[apiKey].update({
          ...formData.value,
          id,
          menu: checkedMenu.join(',')
        }).then(res => {
          if (res.code === 200) {
            ElMessage.success('编辑成功')
            router.back()
          }
        }).finally(() => {
          loadingInstance.close()
        })
      } else {
        // 新增
        http[apiKey].create({
          ...formData.value,
          menu: checkedMenu.join(',')
        }).then(res => {
          if (res.code === 200) {
            ElMessage.success('新增成功')
            router.back()
          }
        }).finally(() => {
          loadingInstance.close()
        })
      }
    } else {
      console.log('error submit!!')
      return false
    }
  })
}
</script>
<template>
  <PageMain :title="id ? '编辑' :'新增'">
    <div class="form-content f-c j-b">
      <div class="form-box form-box3">
        <el-form style="width: 100%" ref="formRef" :model="formData" :rules="rules" label-position="top" >
          <el-form-item label="角色名称" prop="name">
            <el-input clearable v-model="formData.name"></el-input>
          </el-form-item>
          <el-form-item label="权限" style="width: 100%">
            <el-row :gutter="10">
              <el-col :span="24" v-for="item in menuList" style="margin-bottom: 10px">
                <el-card shadow="never">
                  <div class="menu-wrapper f-r a-c">
                    <div class="menu-group-name" style="width: 100px;flex-shrink: 0">{{ item.name }}</div>
                    <div class="menu-list" v-if="item.children">
                      <el-checkbox style="margin-right: 10px;width: 160px" v-for="sub in item.children" v-model="sub.checked">{{ sub.name}}</el-checkbox>
                    </div>
                    <el-checkbox style="width: 160px" v-else v-model="item.checked">{{ item.name }}</el-checkbox>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
      </div>
      <div class="form-button f-s">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="confirm">确认</el-button>
      </div>
    </div>
  </PageMain>
</template>
<style scoped lang="scss">
.form-box3 {
  display: flex;
  .gap {
    width: 32px;
  }
  .el-card__body {
    padding: 10px 20px;
  }
}
</style>
